package com.margo.project.web.mvcconfig.requestbodyadvice;

import java.lang.reflect.Field;
import java.lang.reflect.Type;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;


/**
 * https://www.jianshu.com/p/4e79beee5f64
 * @author fangxingbang
 *
 */
@ControllerAdvice
public class MargoRequestBodyAdvice extends RequestBodyAdviceAdapter {

	private Logger logger=LoggerFactory.getLogger(MargoRequestBodyAdvice.class);	
	
	@Override
	public boolean supports(MethodParameter methodParameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		Boolean support=methodParameter.hasParameterAnnotation(ParamJsonDeserializer.class);
		return support;
	}

	@Override
	public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		if (body != null) {
			ParamJsonDeserializer paramJsonDeserializer = parameter.getParameterAnnotation(ParamJsonDeserializer.class);
			String filedName = paramJsonDeserializer.fieldName();
			Field field;
			try {
				field = body.getClass().getDeclaredField(filedName);
				field.setAccessible(true);
				String value = (String) field.get(body);
	    		field.set(body, deserialize(value,paramJsonDeserializer.length()));
			} catch (Exception e) {
				logger.error("#######属性设置异常######",e);
			} 
			return body;
		} else {
			return body;
		}
	}

	public String deserialize(String value,int length) {
		if (value != null && !StringUtils.isEmpty(value)) {
			String strIds = "";
			String[] objIdLists = StringUtils.split(value, ";");
			if(objIdLists.length==length) {
				return null;
			}
			for (String id : objIdLists) {
				if (!StringUtils.isEmpty(strIds)) {
					strIds = strIds + ",'" + id + "'";
				} else {
					strIds = "'" + id + "'";
				}
			}
			return strIds;
		} else {
			return null;
		}
	}

}
